import { defineStore } from 'pinia';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import {
  getCurrentUserUsingGet,
  userLoginUsingPost,
  userLogoutUsingPost,
} from '@/service/bbeacons-backend/sysUserController';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): API.UserVO => ({
    email: '',
    gender: 0,
    id: undefined,
    phone: '',
    createTime: '',
    updateTime: '',
    userAccount: '',
    userAvatar: '',
    userName: '',
    userRole: '',
  }),

  getters: {
    userInfo(state: API.UserVO): API.UserVO {
      return { ...state };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<API.UserVO>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const res = await getCurrentUserUsingGet();

      this.setInfo(res);
    },

    // Login
    async login(loginForm: API.SysUserLoginRequest) {
      try {
        const res = await userLoginUsingPost(loginForm);
        setToken(res.userToken);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogoutUsingPost();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
